package com.stylefeng.guns.modular.wz.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.stylefeng.guns.common.constant.Consts;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.log4j.Logger;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;


public class WebUtil {

	private static Logger logger = Logger.getLogger(WebUtil.class);


	/**
	 * 根据对象从request中获取相应的属性值
	 * 
	 * @param request
	 * @param clazz
	 * @return
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws InvocationTargetException
	 */
	public static <T> T getObjectFromRequest(ServletRequest request,
			Class<T> clazz) throws InstantiationException,
			IllegalAccessException, InvocationTargetException {
		try {
			T bean = clazz.newInstance();
			@SuppressWarnings("rawtypes")
			Enumeration e = request.getParameterNames();
			while (e.hasMoreElements()) {
				String name = (String) e.nextElement();
				String value = request.getParameter(name);
				if (value != null && value.trim().equals("")) {
					value = null;
				}
				BeanUtils.setProperty(bean, name, value);
			}
			return bean;
		} catch (Exception e) {
			new RuntimeException();
		}
		return null;
	}

	/**
	 * 从request中获取参数的map集合
	 * 
	 * @param request
	 * @return
	 */
	public static Map<String, String> request2Map(ServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		@SuppressWarnings("rawtypes")
		Enumeration e = request.getParameterNames();
		while (e.hasMoreElements()) {
			String name = (String) e.nextElement();
			String value = request.getParameter(name);
			if (value != null && value.trim().equals("")) {
				value = null;
			}
			map.put(name, value);
		}
		return map;
	}


	/**
	 * 获取请求中的文件 针对springMVC框架
	 * 
	 * @param request
	 * @param fileName
	 *            文件名称
	 * @return
	 */
//	public static File getRequestFile(HttpServletRequest request,
//			String fileName) throws IllegalStateException, IOException {
//		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//		// 获取物理路径
//		String path = request.getSession().getServletContext()
//				.getRealPath(Consts.setting.getFileUploadPath());
//		MultipartFile file = multipartRequest.getFile(fileName);
//		if (file != null) {
//			String myFileName = file.getOriginalFilename(); // 原文件名
//			if (myFileName != null && myFileName.trim() != "") {
//				String extName = myFileName.substring(myFileName
//						.lastIndexOf("."));// 文件后缀名，带.的
//				String curFileName = IDUtil.genUUID() + extName;
//				String ymd = DateUtil.toString(new Date(),
//						DateUtil.format_ymd_by_);
//				path = path + "/" + ymd + "/" + curFileName;
//				File localFile = new File(path);
//				if (!localFile.getParentFile().exists()) {
//					localFile.mkdirs();
//				}
//				file.transferTo(localFile);
//				return localFile;
//			}
//		}
//		return null;
//	}



	/**
	 * 获取上传文件的URL路径 针对springmvc框架
	 * 上传文件名
	 * @return 上传文件访问url
	 */
	public static String getRequestFile_savePath(HttpServletRequest request,
			String uploadFileName) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile(uploadFileName);
		try {
			if (file != null) {
				String myFileName = file.getOriginalFilename(); // 原文件名
				if (myFileName != null && myFileName.trim() != "") {
					// 获取物理路径
					String path = request.getSession().getServletContext()
							.getRealPath(Consts.FILE_UPLOAD_PATH);
					String extName = myFileName.substring(myFileName
							.lastIndexOf("."));// 文件后缀名，带.的
					String curFileName = IDUtil.genUUID() + extName;
					String ymd = DateUtil.toString(new Date(),
							DateUtil.format_ymd_by_);
					path = path + "/" + ymd + "/" + curFileName;
					String uri_path = Consts.FILE_UPLOAD_PATH + "/"
							+ ymd + "/" + curFileName;// 文件URI资源路径
					File localFile = new File(path);
					if (!localFile.getParentFile().exists()) {
						localFile.mkdirs();
					}
					file.transferTo(localFile);
					String fileUrl = Consts.FILE_UPLOAD_PATH + uri_path;
					return fileUrl;
				}
			}
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 获取多上传文件的URL路径 针对springmvc框架
	 * 
	 * @param request
	 * @param uploadFileName
	 *            上传文件名
	 * @return 上传文件访问url
	 */
//	public static String[] getRequestFiles_savePath(HttpServletRequest request,
//			String uploadFileName) {
//		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//		Iterator<String> iter = multipartRequest.getFileNames();
//		List<String> paths = new ArrayList<String>();
//		try {
//			while (iter.hasNext()) {
//				// 取得上传文件
//				List<MultipartFile> files = multipartRequest.getFiles(iter
//						.next());
//				for (MultipartFile file : files) {
//					if (file != null && file.getName().equals(uploadFileName)) {
//						String myFileName = file.getOriginalFilename(); // 原文件名
//						if (myFileName != null && myFileName.trim() != "") {
//							// 获取物理路径
//							String path = request
//									.getSession()
//									.getServletContext()
//									.getRealPath(
//											Consts.setting.getFileUploadPath());
//							String extName = myFileName.substring(myFileName
//									.lastIndexOf("."));// 文件后缀名，带.的
//							String curFileName = IDUtil.genUUID() + extName;
//							String ymd = DateUtil.toString(new Date(),
//									DateUtil.format_ymd_by_);
//							path = path + "/" + ymd + "/" + curFileName;
//							String uri_path = Consts.setting
//									.getFileUploadPath()
//									+ "/"
//									+ ymd
//									+ "/"
//									+ curFileName;// 文件URI资源路径
//							File localFile = new File(path);
//							if (!localFile.getParentFile().exists()) {
//								localFile.mkdirs();
//							}
//							file.transferTo(localFile);
//							String fileUrl = Consts.setting.getImgServer()
//									+ uri_path;
//							paths.add(fileUrl);
//						}
//					}
//				}
//			}
//		} catch (IllegalStateException | IOException e) {
//			e.printStackTrace();
//		}
//		return paths.toArray(new String[paths.size()]);
//	}

	/**
	 * 从网页数据中获取图片地址
	 * 
	 * @return
	 */
	public static String[] getImgStrFromHtml(String content) {
		String img = "";
		Pattern p_image;
		Matcher m_image;
		String str = "";
		String[] images = null;
		String regEx_img = "(<img.*src\\s*=\\s*(.*?)[^>]*?>)";
		p_image = Pattern.compile(regEx_img, Pattern.CASE_INSENSITIVE);
		m_image = p_image.matcher(content);
		while (m_image.find()) {
			img = m_image.group();
			Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)")
					.matcher(img);
			while (m.find()) {
				String tempSelected = m.group(1);
				if ("".equals(str)) {
					str = tempSelected;
				} else {
					String temp = tempSelected;
					str = str + "," + temp;
				}
			}
		}
		if (!"".equals(str)) {
			images = str.split(",");
		}
		return images;
	}

	/**
	 * 网页数据转化成纯文本
	 * 
	 * @param inputString
	 * @return
	 */
	public static String Html2Text(String inputString) {
		String htmlStr = inputString; // 含html标签的字符串
		String textStr = "";
		Pattern p_script;
		Matcher m_script;
		Pattern p_style;
		Matcher m_style;
		Pattern p_html;
		Matcher m_html;
		try {
			String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; // 定义script的正则表达式{或<script[^>]*?>[\\s\\S]*?<\\/script>
																										// }
			String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; // 定义style的正则表达式{或<style[^>]*?>[\\s\\S]*?<\\/style>
																									// }
			String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式

			p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);
			m_script = p_script.matcher(htmlStr);
			htmlStr = m_script.replaceAll(""); // 过滤script标签

			p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);
			m_style = p_style.matcher(htmlStr);
			htmlStr = m_style.replaceAll(""); // 过滤style标签

			p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);
			m_html = p_html.matcher(htmlStr);
			htmlStr = m_html.replaceAll(""); // 过滤html标签

			textStr = htmlStr;
		} catch (Exception e) {
			logger.debug("Html2Text: " + e.getMessage());
		}
		return textStr;// 返回文本字符串
	}

	/**
	 * 是否是安全请求
	 * 
	 * @param request
	 * @param second
	 *            安全时间（秒）
	 * @return
	 */
	public static boolean isSafeHttpRequest(HttpServletRequest request,
			int second) {
		HttpSession session = request.getSession();
		String ip = request.getRemoteHost();
		String _ip = session.getAttribute("_ip") == null ? null
				: (String) session.getAttribute("_ip");
		long _lastReqTime = session.getAttribute("_lastReqTime") == null ? 0
				: (long) session.getAttribute("_lastReqTime");
		if (_ip == null || _lastReqTime == 0) {
			session.setAttribute("_ip", ip);
			session.setAttribute("_lastReqTime", new Date().getTime());
			return true;
		} else {
			if ((new Date().getTime() - _lastReqTime) > (second * 1000)) {
				session.setAttribute("_lastReqTime", new Date().getTime());
				return true;
			} else {
				return false;
			}
		}
	}

	/**
	 * 获取完整URL地址
	 * 
	 * @param request
	 * @return
	 */
	public static String getFullUrl(HttpServletRequest request) {
		return request.getRequestURL().toString()
				+ (request.getQueryString() == null ? "" : ("?" + request
						.getQueryString()));
	}

	/**
	 * 验证是否是手机
	 * 
	 * @param str
	 * @return
	 */
	public static boolean isMobile(String str) {
		Pattern p = null;
		Matcher m = null;
		boolean b = false;
		p = Pattern
				.compile("^(13[0-9]|14(5|7)|15(0|1|2|3|5|6|7|8|9)|17[0-9]|18[0-9])\\d{8}$"); // 验证手机号
		m = p.matcher(str);
		b = m.matches();
		return b;
	}

	/**
	 * 随机数
	 * 
	 * @param r
	 * @return
	 */
	public static int random(int r) {
		return (int) (Math.random() * r + 1);
	}

	/**
	 * 数组转字符
	 * 
	 * @return
	 */
	public static String arrayToString(String[] ss, String s) {
		if (s == null) {
			s = "";
		}
		StringBuilder sb = new StringBuilder();
		for (int i = 0; ss != null && i < ss.length; i++) {
			sb.append(ss[i].trim()).append(s);
		}
		if (ss != null && ss.length > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}

	/**
	 * 获取域名
	 * 
	 * @param request
	 * @return
	 */
	public static String getDomain(HttpServletRequest request) {
		StringBuffer url = request.getRequestURL();
		return url
				.delete(url.length() - request.getRequestURI().length(),
						url.length()).append("/").toString();
	}

	/**
	 * @param biz_content
	 */
	public static String map2String(Map<String, String> biz_content, String s) {
		ArrayList<String> list = new ArrayList<String>();
		for (Entry<String, String> obj : biz_content.entrySet()) {
			list.add(obj.getKey() + "=" + obj.getValue() + "&");
		}
		int size = list.size();
		String[] arrayToSort = list.toArray(new String[size]);
		Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < size; i++) {
			sb.append(arrayToSort[i]);
		}
		if (size > 0) {
			sb.deleteCharAt(sb.length() - 1);
		}
		return sb.toString();
	}


	/**
	 * 是否是邮箱
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		Pattern regex = Pattern.compile(check);
		Matcher matcher = regex.matcher("dffdfdf@qq.com");
		boolean isMatched = matcher.matches();
		return isMatched;
	}

	/*
	 * @auther:yxs
	 */
	public static void download(String path,HttpServletRequest request, HttpServletResponse response) {
		try {
			// path是指欲下载的文件的路径。
			File file = new File(path);
			// 取得文件名。
			String filename = file.getName();
			// 以流的形式下载文件。
			InputStream fis = new BufferedInputStream(new FileInputStream(path));
			byte[] buffer = new byte[fis.available()];
			fis.read(buffer);
			fis.close();
			// 清空response
			//response.reset();
			// 设置response的Header
			//response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(filename, "UTF-8"));  
			String agent = request.getHeader("User-Agent");
			// 判断是哪种浏览器发送的请求,对文件名进行响应的编码设置
            if (agent.toLowerCase().indexOf("firefox") > 0) {
            	filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
            }
            //IE
            else if (agent.toUpperCase().indexOf("MSIE") > 0){
            	filename = URLEncoder.encode(filename, "UTF-8");
            }else{
            	filename = URLEncoder.encode(filename, "UTF-8");
            }
             
            response.setHeader("Content-Disposition", "attachment;filename=\""+filename+"\"");
			//response.addHeader("Content-Length", "" + file.length());
			OutputStream toClient = new BufferedOutputStream(
					response.getOutputStream());
			String name = file.getName();
			String str=name.substring(name.lastIndexOf(".")+1); 
			response.setContentType("application/"+str+";charset=utf-8");
			toClient.write(buffer);
			toClient.flush();
			toClient.close();
		} catch (IOException ex) {
			ex.printStackTrace();
		}
	}
}
